let path = require("path");
let glob = require("glob");
let merge = require("webpack-merge");
let pagePath = path.resolve(__dirname, "../pages");
let HtmlWebpackPlugin = require("html-webpack-plugin");

exports.pages = function() {
  let map = {};
  let entryFiles = glob.sync(pagePath + "/*/*.js");
  entryFiles.forEach(filePath => {
    let filename = filePath.substring(
      filePath.lastIndexOf("/") + 1,
      filePath.lastIndexOf(".")
    );
    let docPath = filePath.substring(0, filePath.lastIndexOf("/"));
    map[filename] = {
      entry: filePath,
      // 模板来源
      template: `${docPath}/${filename}.html`,
      // 在 dist/index.html 的输出
      filename: `${filename}.html`,
      // 当使用 title 选项时，
      // template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: "Index Page",
      // 在这个页面中包含的块，默认情况下会包含
      // 提取出来的通用 chunk 和 vendor chunk。
      chunks: ["chunk-vendors", "chunk-common", filename]
    };
  });
  return map;
};

exports.htmlPlugin = function() {
  let plugin = [];
  let templates = glob.sync(pagePath + "/*/*.html");
  templates.forEach(template => {
    let filename = template.substring(
      template.lastIndexOf("/") + 1,
      template.lastIndexOf(".")
    );
    let docPath = template.substring(0, template.lastIndexOf("/"));
    let confing = {
      template: template,
      filename: `${filename}.html`,
      hash: true,
      favicon: `${docPath}/favicon.ico`,
      title: filename.toLocaleUpperCase(),
      chunks: ["chunk-vendors", "chunk-common", filename]
    };

    if ((process.env.NODE_ENV = "production")) {
      confing = merge(confing, {
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          removeAttributeQuotes: true
        },
        chunksSortMode: "dependency"
      });
    }
    plugin.push(new HtmlWebpackPlugin(confing));
  });

  return plugin;
};
